﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using wjy自制小框架.Common.Pojo;

namespace wjy自制小框架.Common.Mapper
{
    /// <summary>
    /// 提供Sql快捷功能
    /// wjy
    /// </summary>
    class BaseMapper<T>
    {
        private string tableName;

        public BaseMapper() { tableName = typeof(T).Name; }

        /// <summary>
        /// 新增
        /// </summary>
        public long insert(T entity)
        {
            if (entity == null) throw new Exception("待新增数据不能为空");
            insertBatch(new List<T>() { entity });
            var list = Db.Connect($"select max(ID) as 'maxId' from { tableName }");
            long maxId = list[0]["maxId"];
            return maxId;
        }

        /// <summary>
        /// 批量新增
        /// </summary>
        public void insertBatch(List<T> entitys)
        {
            if (entitys.Count < 1) return;
            var Modes = JsonConvert.DeserializeObject<List<Dictionary<string, object>>>(JsonConvert.SerializeObject(entitys));
            var keys = "";
            var values = "";
            for (int i = 0; i < Modes.Count; i++)
            {
                var mode = Modes[i];
                var value = "";
                foreach (var e in mode)
                {
                    if (e.Key == "ID") continue; // 插入时不需要id
                    if (i == 0) keys += $"`{ e.Key }`,"; // 第一行收集待插字段
                    if (e.Value == null || e.Value.ToString() == "")
                        value += "'',";
                    else
                        value += $"'{ e.Value }',";
                }
                value = value.TrimEnd(',');
                values += $"({ value }),";
            }
            keys = keys.TrimEnd(',');
            values = values.TrimEnd(',');
            string Sql = $"insert into { tableName } ({ keys }) values " + values;
            Db.Connect(Sql);
        }

        /// <summary>
        /// 根据ID更新
        /// </summary>
        public void updateById(T entity)
        {
            var Mode = JsonConvert.DeserializeObject<Dictionary<string, object>>(JsonConvert.SerializeObject(entity));
            update(entity, new QueryWrapper().eqIfPresent("ID", Mode["ID"]));
        }

        /// <summary>
        /// 根据ID批量更新
        /// </summary>
        public void updateBatchById(List<T> entitys)
        {
            if (entitys.Count < 1) return;
            var Modes = JsonConvert.DeserializeObject<List<Dictionary<string, object>>>(JsonConvert.SerializeObject(entitys));
            var Sql = "";
            foreach (var mode in Modes)
            {
                var update = "";
                foreach (var e in mode)
                {
                    if (e.Key == "ID") continue;
                    string val = e.Value == null ? "" : e.Value.ToString();
                    update += $"`{ e.Key }` = '{ val }',";
                }
                update = update.TrimEnd(',');
                Sql += $"update { tableName } set { update } where ID = '{ mode["ID"] }';";
            }
            Db.Connect(Sql);
        }

        /// <summary>
        /// 更新
        /// </summary>
        public void update(T entity, QueryWrapper updateWrapper)
        {
            var where = updateWrapper.buildSql();
            if (string.IsNullOrEmpty(where)) return;
            var Modes = JsonConvert.DeserializeObject<Dictionary<string, object>>(JsonConvert.SerializeObject(entity));
            var update = "";
            foreach (var e in Modes)
            {
                if (e.Key == "ID") continue;
                string val = e.Value == null ? "" : e.Value.ToString();
                update += $"`{ e.Key }` = '{ val }',";
            }
            update = update.TrimEnd(',');
            Db.Connect($"update { tableName } set { update } { where }");
        }

        /// <summary>
        /// 根据ID删除
        /// </summary>
        public void deleteById(string id)
        {
            Db.Connect($"delete from { tableName } where ID = '{ id }'");
        }

        /// <summary>
        /// 根据IDS删除
        /// </summary>
        public void deleteBatchIds(string[] idList)
        {
            if (idList.Length < 1) return;
            Db.Connect($"delete from { tableName } where ID in ({ string.Join(",", idList) })");
        }

        /// <summary>
        /// 删除
        /// </summary>
        public void delete(QueryWrapper queryWrapper)
        {
            var where = queryWrapper.buildSql();
            if (string.IsNullOrEmpty(where)) return;
            Db.Connect($"delete from { tableName } { where }");
        }


        /// <summary>
        /// 查询分页
        /// </summary>
        public AjaxResult selectPage(PageParam page, QueryWrapper queryWrapper) {
            int start = (page.pageNo - 1) * page.pageSize;
            int end = page.pageNo * page.pageSize - 1;
            var where = queryWrapper.buildSql();
            var list = Db.Connect($"select * from { tableName } { where } limit { start },{ end };");
            var total = selectCount(queryWrapper);
            return AjaxResult.page(list, total);
        }

        /// <summary>
        /// 根据ID查询
        /// </summary>
        public T selectById(string id)
        {
            return selectOne("ID", id);
        }

        /// <summary>
        /// 根据IDS查询
        /// </summary>
        public List<T> selectBatchIds(List<string> idList)
        {
            return selectList(new QueryWrapper().inIfPresent("ID", idList));
        }

        /// <summary>
        /// 查询一条记录
        /// </summary>
        public T selectOne(string field, object value)
        {
            return selectOne(new QueryWrapper().eqIfPresent(field, value));
        }

        /// <summary>
        /// 查询一条记录
        /// </summary>
        public T selectOne(string field1, object value1, string field2, object value2)
        {
            return selectOne(new QueryWrapper().eqIfPresent(field1, value1).eqIfPresent(field2, value2));
        }

        /// <summary>
        /// 查询一条记录
        /// </summary>
        public T selectOne(QueryWrapper queryWrapper)
        {
            var list = Db.Connect($"select * from { tableName } { queryWrapper.buildSql() } limit 1");
            return list.Count > 0 ? JsonConvert.DeserializeObject<T>(JsonConvert.SerializeObject(list[0])) : null;
        }

        /// <summary>
        /// 查询总数
        /// </summary>
        public long selectCount()
        {
            return selectCount(new QueryWrapper());
        }

        /// <summary>
        /// 查询总数
        /// </summary>
        public long selectCount(string field, object value)
        {
            return selectCount(new QueryWrapper().eqIfPresent(field, value));
        }

        /// <summary>
        /// 查询总数
        /// </summary>
        public long selectCount(QueryWrapper queryWrapper)
        {
            var list = Db.Connect($"select count(0) as 'total' from { tableName } { queryWrapper.buildSql() }");
            long total = list[0]["total"];
            return total;
        }

        /// <summary>
        /// 查询集合列表
        /// </summary>
        public List<T> selectList()
        {
            return selectList(new QueryWrapper());
        }

        /// <summary>
        /// 查询集合列表
        /// </summary>
        public List<T> selectList(string field, object value)
        {
            return selectList(new QueryWrapper().eqIfPresent(field, value));
        }

        /// <summary>
        /// 查询集合列表
        /// </summary>
        public List<T> selectList(string field1, object value1, string field2, object value2)
        {
            return selectList(new QueryWrapper().eqIfPresent(field1, value1).eqIfPresent(field2, value2));
        }

        /// <summary>
        /// 查询集合列表
        /// </summary>
        public List<T> selectList(QueryWrapper queryWrapper)
        {
            var list = Db.Connect($"select * from { tableName } { queryWrapper.buildSql() }");
            return JsonConvert.DeserializeObject<List<T>>(JsonConvert.SerializeObject(list));
        }
    }
}
